/*<![CDATA[*/
var navigation = function(){
	var it = this;

	this.target = null;
	this.fstMnIdx = null;
	this.fstSubIdx = null;

	this.curIdx = null;
	this.subCurIdx = null;

	this.preIdx = null;
	this.subPreIdx = null;
	this.timer = new Array();

	this.init = function(){
		$(it.target+">li>a").each(function(i){
			if($(it.target+">li>a").eq(i).hasClass("on")){
				it.fstMnIdx = i;
				it.preIdx = i;
			}

			$(it.target+">li>ul>li>a").each(function(k){
				if($(it.target+">li>ul>li>a").eq(k).hasClass("on")){
					it.fstSubIdx = k;
					it.subPreIdx = k;
				}
			});
		});
		//alert("First M-Menu Index : "+it.fstMnIdx+"\nFirst S-Menu Index : "+it.fstSubIdx);
	};

	this.out = function(pos){
		$(it.target+">li>a").eq(pos).removeClass("on");
		$(it.target+">li>a").eq(pos).parent().find("ul").removeClass("on");
		$(it.target+">li>ul>li>a").eq(it.subPreIdx).removeClass("on")

		$(it.target+">li>a").eq(it.fstMnIdx).addClass("on");
		$(it.target+">li>a").eq(it.fstMnIdx).parent().find("ul").addClass("on");
		$(it.target+">li>ul>li>a").eq(it.fstSubIdx).addClass("on")
	};

	this.run = function() {
		$(it.target+">li>a").each(function(i) {
			$(it.target+">li>a").eq(i).bind("mouseenter focus",function() {
				clearTimeout(it.timer.mn);
				clearTimeout(it.timer.sub);

				it.curIdx=i;
				if(it.preIdx !==i){
					$(it.target+">li>a").eq(it.preIdx).removeClass("on");
					if($(it.target+">li>a").eq(it.preIdx).parent().find("ul").attr("class")=="on") {
						$(it.target+">li>a").eq(it.preIdx).parent().find("ul").removeClass("on");
					}
					$(it.target+">li>a").eq(i).addClass("on");
					$(it.target+">li>a").eq(i).parent().find("ul").addClass("on");
					it.preIdx = i;
				}else{
					if($(it.target+">li>a").eq(i).parent().find("ul").attr("class")=="") {
						$(it.target+">li>a").eq(i).parent().find("ul").removeClass("on");
					}
				}
			});
			$(it.target+">li>a").eq(i).bind("mouseleave blur",function() {
				it.timer.mn = setTimeout(function(){it.out(i);},2000);
			});
		});

		$(it.target+">li>ul>li>a").each(function(k){
			$(it.target+">li>ul>li>a").eq(k).bind("mouseenter focus",function(){
				clearTimeout(it.timer.mn);
				clearTimeout(it.timer.sub);

				it.subCurIdx = k;
				if(it.subPreIdx != k){
					$(it.target+">li>ul>li>a").eq(k).addClass("on");

					if(it.subPreIdx != null){
						$(it.target+">li>ul>li>a").eq(it.subPreIdx).removeClass("on");
					}
					it.subPreIdx = k;
				}
			});

			$(it.target+">li>ul>li>a").eq(k).bind("mouseleave blur",function(){
				it.subCurIdx = k;
				it.timer.sub = setTimeout(function(){it.out(it.curIdx);},2000);
			});
		});
	}
};

/**
 * 검역기관 목록 조회
 */
function getInsttOrgnztCode(val){
	if(val===0){
		return;
	}else{
		$.ajax({
			type:"post",
			url:"/common/code/insttOrgnztList.ajax",
			data:{"upperCode":val},
			dataType:"json",
			error:function(request,status,error){
				alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
			},
			success:function(data){
				var options="<option value=\"0\">:: 선택 ::</option>";
				$.each(data,function(key,value){
					for(var i in value){
						if(typeof value[i].code != "undefined"){
							options +="<option value=\""+value[i].code+"\">"+value[i].name+"</option>";
						}
					}
				});
				$("#offCd").html(options);
			}
		});
	}
}

function openLayer(openUrl){
	var offTop = $(document).scrollTop();
	$("#uploadFrame").remove();
	$.ajax({
		url: openUrl,
		type: 'GET',
		dataType:'html',
		success: function(html){
			var w = $(window).width() > $("#wrap_sub").width() ? $(window).width() : $("#wrap_sub").width();
			var h = $(window).height() > $("#wrap_sub").height() ? $(window).height() : $("#wrap_sub").height();
			$("body").append("<div class=\"bgScreen\" style=\"height:"+h+"px; min-width:100%; width:"+w+"px\"></div>").append(html);

			var layer = $("#"+$(".layerPopup").attr("id"));
			$(layer).css("top",'+='+offTop);
		}
	});
}

function closeLayer(target,targetFrame){
	$(".bgScreen").remove();
	$(target).remove();
	$(targetFrame).remove();
}

/**
 * @returns row(tr) count in table
 */
function checkRowCount(target){
	return $(target).find("input[name=\"data\"]").length;
}

/**
 * 데이터 입력 체크
 */
function checkRowData(target){
	var temp = [];
	var i=0;
	$(target).find("input[name=\"itemQty\"]").each(function(idx){
		if(!isNull($(this).val())){
			temp[i] = $(this).val();
			i++;
		}
	});
	return temp.length;
}

/**
 * 목록의 전체 선택 및 해제
 */
function allDataChk(target){

	if(checkRowCount(target)==0){
		alert("데이터가 없습니다.");
		return;
	}

	var count=0;
	var data = $(target).find("input[name=\"data\"]");
	var dataLength = data.length;
	for(var i=0; i<dataLength; i++){
		if(data[i].checked==true) count++;
	}
	if(count>=0 && count<dataLength){
		for(var i=0; i<dataLength; i++){
			data[i].checked = true;
		}
	}else if(count==dataLength){
		for(var i=0; i<dataLength; i++){
			data[i].checked = false;
		}
	}
}

function reTryTotal(target){
	getTotalQty(target);

	$(target).find("input[name=\"itemQty\"]").blur(function(){
		getTotalQty(target);
	});

	$(target).find("select[name=\"qunCode\"]").change(function(){
		getTotalQty(target);
	});
}

/**
 * sum item amount
 */
function getTotalQty(target){
	var total=0;
	var wTot = 0;
	var mTot = 0;
	var cTot = 0;
	var tTot = 0;
	var vTot = 0;
	var qunCodeList = $(target).find("select[name=\"qunCode\"]");
	$(target).find("input[name=\"itemQty\"]").each(function(i){
		var qty = $(this).val();
		if(!isNull(qty) && isNumber(parseInt(qty))){
			switch(qunCodeList.eq(i).val()){
			case "117001": case "249003":	//kg => 중량 [mg*1000*1000]
				wTot += parseInt(qty,10);
				break;
			case "117002": case "249004":	// g => 중량 [mg*1000]
				wTot += parseInt(qty,10)/1000;
				break;
			case "117003": case "249008":	//㎥ : 부피 => 수량
				mTot += parseInt(qty,10);
				break;
			case "117004": case "249005":	// mg => 중량
				wTot += parseInt(qty,10)/1000/1000;
				break;
			case "117005": case "249010":	// 개 => 수량
				cTot += parseInt(qty,10);
				break;
			case "117006":	// M/T : meter/ton => 수량
				tTot += parseInt(qty,10);
				break;
			case "117007": case "249007":	// vial : 유리병 => 수량
				vTot += parseInt(qty,10);
				break;
			}
		}
	});
	var temp = [];
	var idx = 0;
	if(wTot!=0) {
		temp[idx] = wTot.toFixed(3)+"kg";
		idx++;
	}
	if(mTot!=0){
		temp[idx] = mTot+"㎥";
		idx++;
	}
	if(cTot!=0){
		temp[idx] = cTot+"개";
		idx++;
	}
	if(tTot!=0){
		temp[idx] = tTot+"M/T";
		idx++;
	}
	if(vTot!=0){
		temp[idx] = vTot+"vial";
	}
	total = temp.join(",");
	$(target).find("input[name=\"totQty\"]").val(total);
}

/**
 * 총 품목수
 */
function getItemCount(target){
	var i=0;
	var temp = [];
	$(target).find("input[name=\"prdlstName\"]").each(function(idx){
		var data = $(this).val();
		if(!isNull(data)){
			temp[i] = data;
			i++;
		}
	});
	$(target).find("select[name=\"itemCode\"]").each(function(idx){
		var data = $(this).val();
		if(!isNull(data)){
			temp[i] = data;
			i++;
		}
	});

	temp.unique();
	$(target).find("input[name=\"itemCount\"]").val(temp.length);
}

/**
 * Add table row
 */
function addRow(target){

	if(checkRowCount(target)==0){
		$(target).find("#noData").remove();
	}

	$(target).find("tbody").append(row);

	$(target).find("input[name=\"itemQty\"]").blur(function(){
		var value = $(this).val();
		if(value.length==0){
			$(this).val("0").focus();
		}else{
			if(!isNumber(value)){
				alert("숫자만 입력 가능합니다.");
				$(this).val("0").focus();
			}else{
				$(this).val(parseInt(value));
			}
		}
		getTotalQty(target);
		getItemCount(target);
	});
	$(target).find("select[name=\"qunCode\"]").change(function(){
		getTotalQty(target);
	});
	$(target).find("input[name=\"prdlstName\"]").blur(function(){
		getItemCount(target);
	});
}


/**
 * delete table row
 */
function delRow(target){
	var data = $(target).find("input[name=\"data\"]");
	if(checkRowCount(target)==0){
		alert("삭제할 데이터가 없습니다.");
		return;
	}

	var idx = [];
	var count = 0;

	for(var i=0;i<data.length;i++){
		if(data[i].checked==true) {
			idx[count] = i;
			count++;
		}
	}

	if(idx.length==0){
		alert("삭제하실 데이터를 선택하세요");
		return;
	}else if(idx.length == data.length){
		if(!confirm("전체 데이터를 삭제하시겠습니까?")){
			return;
		}
	}

	for(var k=(idx.length-1);k>=0 && k<idx.length;k--){
		$(target).find("tbody>tr").eq(idx[k]).remove();
	}

	if(checkRowCount(target)==0){
		var colCnt = $(target).find("thead tr:eq(0) th").length;
		var spanCnt=0;
		$(target).find("thead tr:eq(0) th").each(function(idx){
			if(typeof $(this).attr("colspan") != "undefined"){
				spanCnt += parseInt($(this).attr("colspan"),10)-1;
			}
		});
		colCnt += spanCnt;
		var noData = "";
		noData += "<tr id=\"noData\">\n";
		noData += "	<td colspan=\""+colCnt+"\" class=\"tCenter bdLeftNone\">화물정보를 입력하세요.</td>\n";
		noData += "</tr>\n";
		$(target).find("tbody").append(noData);
	}

	getTotalQty(target);
	getItemCount(target);
}

function toggleUploadButton(){
	$("#popup").find("input[name=\"upFile\"]").change(function(){
		if(!isNull($(this).val())){
			$("input.uploadBtn").fadeIn("fast");
		}
	});
}

// check null value
function isNull(str) {
	if (str.replace(/\s/g, '') == '') {
		return true;
	}
	return false;
}

// check email
function noEmail(obj) {
	var check1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;

	var check2 = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/;

	if (!check1.test(obj.value) && check2.test(obj.value)) {
		return true;
	} else {
		return false;
	}
}

/**
 * 날짜비교
 */
function compareDate(std,target){
	var stdDate = new Date(std[0],std[1]-1,std[2]);
	var targetDate = new Date(target[0],target[1]-1,target[2]);
	if(stdDate>targetDate){
		return false;
	}else if(stdDate<=targetDate){
		return true;
	}
}

function isNumber(str){
	var regex = /[^0-9.]/g;
	if(regex.test(str)){
		return false;
	}else{
		return true;
	}
}
/*
function isNumber(value) {
	return typeof value === 'number' && isFinite(value);
}
*/

// 공백제거
function trim(str) {
	var whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
	for (var i = 0; i < str.length; i++) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(i);
			break;
		}
	}
	for (i = str.length - 1; i >= 0; i--) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

//10보다 작으면 앞에 0을 붙임
function addzero(n) {
 return n < 10 ? "0" + n : n;
}

/**
 *
 * @returns {Boolean}
 */
function getByteLength( data ) {
	var len = 1;
	var str = data.substring(0);

	if ( str == null ) return 0;

	for(var i=0; i < str.length; i++) {
		var ch = escape(str.charAt(i));

		if( ch.length == 1 ) len++;
		else if( ch.indexOf("%u") != -1 )  len += 2;//Db가 한글을 3byte로 인식하여 2->3
		else if( ch.indexOf("%") != -1 ) len += ch.length/3;
	}

	return len;
}

function getSubStringByLength(data,length){
	var len = 1;
	var str = data.substring(0);

	var returnStr = "";
	for(var i=str.length,j=0; i >0; i--,j++) {
		var ch = escape(str.charAt(j));
		if( ch.length == 1 ) len++;
		else if( ch.indexOf("%u") != -1 )  len += 2;//Db가 한글을 3byte로 인식하여 2->3
		else if( ch.indexOf("%") != -1 ) len += ch.length/3;

		if(len<length){
			returnStr += str.charAt(j);
		}else{
			break;
		}
	}
	return returnStr;
}

//길이 체크 시작
function checklength() {
	var params = new Array();
	var argsize = 0;
	var msg="";
	if(arguments.length<2) return false;

	argsize = arguments.length;
	for(var i=0;i<arguments.length;i++){
		params[i] = arguments[i];
	}

	switch(argsize){
	case 2:
		msg = '영문 최대 ' + params[1]+ '자,\n한글 최대 '+(params[1]/2)+'자로 입력하세요.';
		break;
	case 3:
		msg = '영문 최소 ' + params[1] + '자 최대 ' + params[2]+ '자\n';
		msg += '한글  최소 ' + params[1] + '자 최대 ' + (params[1]/2)+ '자로 입력하세요.';
		break;
	default:
		msg = "";
	}

	if(argsize==2){
		if (getByteLength(params[0]) > params[1]) {
			alert(msg);
			return false;
		}
	}else if(argsize==3){
		if (getByteLength(params[0]) < params[1] || getByteLength(params[0]) > params[2]) {
			alert(msg);
			return false;
		}
	}
	return true;

}

/**
 * set Cookie
 * @param name
 * @param value
 * @param expiredays
 */
function setCookie(name, value, expiredays) {
	var todayDate = new Date();
	todayDate.setDate(todayDate.getDate() + expiredays);
	document.cookie = name + "=" + escape(value) + "; path=/; expires="
		+ todayDate.toGMTString() + ";";
}

/**
 * get Cookie
 * @param name
 * @returns
 */
function getCookie(name) {
	var nameOfCookie = name + "=";
	var x = 0;
	while (x <= document.cookie.length) {
		var y = (x + nameOfCookie.length);
		if (document.cookie.substring(x, y) == nameOfCookie) {
			if ((endOfCookie = document.cookie.indexOf(";", y)) == -1) {
				endOfCookie = document.cookie.length;
			}
			return unescape(document.cookie.substring(y, endOfCookie));
		}

		x = document.cookie.indexOf(" ", x) + 1;
		if (x == 0) {
			break;
		}
	}
	return "";
}

/**
 * get message
 * @param type [error or notice]
 * @param code code value
 */
function getMessage(type,code){
	return messageList[type][code];
}

/**
 * 로딩 이미지 표시
 */
function showLoading() {
	$.blockUI({
		message: '<img src="/images/common/loading.gif" alt="loading" />',
		css: {
			border: 'none',
			width: '198px',
			height: '198px',
			top: ($(window).height() / 2 - 100) + 'px',
			left: ($(window).width() / 2 - 100) + 'px'
		},
		opacity: 0
	});
}

function openPopLink(url,type){
	var width = 600;
	var height = 400;

	switch(type){
	case 'nation':
		width=640;
		height=700;
		break;
	case 'bose': case 'company': case 'product':
		width=520;
		height=660;
		break;
	case 'zipcode':
		width=640;
		height=660;
		break;
	case 'sms': case 'ipin': case 'gpin':
		width=240;
		height=360;
		break;
	case 'qrant': case 'hsCode':
		width=520;
		height=600;
		break;
	case 'pass':
		width=470;
		height=300;
		break;
	case 'dsnf':
		width=640;
		height=650;
		break;
	case 'idInfo':
		width=370;
		height=120;
		break;
	default:
		width = 480;
		height = 600;
	}

	window.open(url,type,"width="+width+",height="+height+",scrollbars=yes,resizable=no");
}

/**
 * 팝업 선택 값 부모창으로 셋팅
 */
function setSearchResultData(field,value){
	var idx =  0;
	if(arguments.length==3){
		idx = arguments[2];
	}
	switch(field){
	case "natCd":
		$("input[name=\"natCd\"]").val(value.nationCode);
		$("#natName").val(value.korName);
		$("input[name=\"natIsoCode\"]").val(value.isoCode);
		break;
	case "orgNatCd":
		$("input[name=\"orgNatCd\"]").val(value.nationCode);
		$("#orgNatName").val(value.korName);
		$("input[name=\"orgNatIsoCode\"]").val(value.isoCode);
		break;
	case "pasNatCd":
		$("input[name=\"pasNatCd\"]").val(value.nationCode);
		$("#pasNatName").val(value.korName);
		$("input[name=\"pasNatIsoCode\"]").val(value.isoCode);
		break;
	case "bose":
		$("input[name=\"boseNo\"]").val(value.boseNo);
		$("input[name=\"insPlace\"]").val(value.insPlace);
		break;
	case "venZip":
		var zipcode = value.zipCode.split("-");
		$("#venZipCodeFr, #impZipCodeFr").val(zipcode[0]);
		$("#venZipCodeEd, #impZipCodeEd").val(zipcode[1]);
		$("#venRnCode, #impRnCode").val(value.rnCd);
		$("#venRnAdres, #impRnAdres").val(value.rnAdres);
		$("#venLegalCode, #impLegalCode").val(value.amdCd);
		$("#venLegalAdres, #impLegalAdres").val(value.lnmAdres);
		break;
	case "addZip":
		var zipcode = value.zipCode.split("-");
		$("#venZipCodeFr2").val(zipcode[0]);
		$("#venZipCodeEd2").val(zipcode[1]);
		$("#venRnCode2").val(value.rnCd);
		$("#venRnAdres2").val(value.rnAdres);
		$("#venLegalCode2").val(value.amdCd);
		$("#venLegalAdres2").val(value.lnmAdres);
		break;
	case "company":
		$("#tsqNo").val(value.tsqNo);
		$("#venCode").val(value.venCode);
		$("#venKorName").val(value.venKorName);
		$("#venEngName").val(value.venEngName);
	case "hsCode":
		if(arguments.length==3){
			$("input[name=\"hsCode\"]").eq(idx).val(value.hsCode);
		}else{
			$("input[name=\"hsCode\"]").val(value.hsCode);
		}
		break;
	case "dsnf":
		$("#dsnfComCode").val(value.comCode);
		$("#dsnfComName").val(value.comName);
		$("#dsnfCeoName").val(value.ceoName);
		$("#venNameEng").val(value.entrpsEngNm);
		$("#venBizrNo").val(value.bizrno);
		$("#venTelNo").val(value.telNo);
		$("#venFaxNo").val(value.fxnum);
		$("#venZipCode").val(value.bplcZip);
		$("#venZipCodeFr").val(value.bplcZip.substring(0,3));
		$("#venZipCodeEd").val(value.bplcZip.substring(3));
		$("#venLegalAdres").val(value.bplcAdres);
		$("#venLegalDetailAdres").val(value.bplcDetailAdres);
		$("#venEngAdres").val(value.bplcEngAdres);
		$("#venRnCode").val(value.bplcRnCode);
		$("#venRnAdres").val(value.bplcRnAdres);
		$("#venLegalDetailAdres").val(value.bplcRnDetailAdres);
		$("#venCeoNmEng").val(value.rprsntvEngNm);
		$("#venCeoBirth").val(value.ihidnum.substring(2));
		$("#select_year_dob").val(value.ihidnum.substring(2,4));
		$("#select_month_dob").val(value.ihidnum.substring(4,6));
		$("#select_day_dob").val(value.ihidnum.substring(6));
	}
}

/**
 *  Multi-DataPicker 설정
 */
function setDatepicker(){
	var targets = $("form").find(".inputDate");
	if(targets.length !==0){
		targets.datepicker({
			showOn:"button",
			buttonImage:"/images/icon/calendar.gif",
			buttonImageOnly:true
		});
	}
}

/**
 * 배열의 중복값 제거
 */
Array.prototype.unique = function(){
	var a = {};
	for(var i=0; i <this.length; i++){
		if(typeof a[this[i]] == "undefined")
			a[this[i]] = 1;
	}
	this.length = 0;
	for(var i in a){
		this[this.length] = i;
	}
	return this;
};

$(function(){
	var GNB = new navigation();
	GNB.target = "#GNB";
	GNB.init();
	GNB.run();

	setDatepicker();
});


/*========== 이벤트 ============*/
/*해당 타입의 입력방식을 숫자만 입력가능하게하는 이벤트*/
$.fn.onlyNum = function(){
	$(this).css('ime-Mode','disabled');

	$(this).keypress(function (event) {
		var eCode = event.keyCode;

        if (!( eCode == 46 || (( eCode > 47 && eCode < 58 )) )) {
            event.preventDefault();
        }
		return $(this);
	});
};

//현재날짜 구하기
function todayVal(){
	var d = new Date();
	var today = leadingZeros(d.getFullYear(), 4) + '-' + leadingZeros(d.getMonth() + 1, 2) + '-' + leadingZeros(d.getDate(), 2);
	return today;
}


//달력 0 설정
var leadingZeros = function(n, digits) {//달력 0설정
	var zero = '';
	n = n.toString();
	if (n.length < digits) {
	    for (i = 0; i < digits - n.length; i++)
	        zero += '0';
	    }
  return zero + n;
};

/*]]>*/